﻿using Blm.VisionCloud.FrameWork.Cached;
using Language.Resource;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json.Linq;
using Swashbuckle.AspNetCore.Annotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VisionCloud.Api.Common;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.Data;
using VisionCloud.Domain.DtoModel.Ms;
using VisionCloud.Domain.Filters;
using VisionCloud.Service.Ms;

namespace VisionCloud.Api.Controllers.Ms
{
    /// <summary>
    /// 标准库
    /// </summary>
    [SystemModule("标准库相关")]
    [ApiAuthorize(PolicyEnum.RequireRolePermission)]
    [ApiVersion("1.0")]
    [Route("api/ms/[controller]/[Action]")]
    [ApiExplorerSettings(GroupName = "标准库相关")]
    public class StandardController : ApiBaseController
    {
        public ICached Cached { get; set; }

        public StandardService StandardService { get; set; }

        /// <summary>
        /// 多语言资源
        /// </summary>
        public IStringLocalizer<ControllerResource> localizer { get; set; }

        /// <summary>
        /// 获取建筑工艺
        /// </summary>
        /// <param name="obj">字段 standardId,addDefault=false</param>
        /// <returns></returns>
        [HttpPost]
        public Task<ApiResult> GetBuildingCraft(JObject obj)
        {
            return TryCatch(async () =>
            {
                var standardId = obj.GetAndCheck<Guid>("standardId");
                var addDefault = obj.GetAndCheck<bool>("addDefault", false, false);
                var projectId = obj.GetAndCheck<Guid>("projectGuid", false, false);
                var cache = Cached.GetOrSet(GetOpenApiName(), () =>
                {
                    var list = DataStore.GetStandards(projectId);
                    return list.Select(w => new SelectItem(w.Stage, w.ProjectStandardId.ToString())).ToList();
                }, DataStore.GetCommonTimeSpan());

                var standardEntity = cache.Single(w => w.Value == standardId.ToString());
                var items = Dict.BuildingCraft.Where(w => w.FirstLv.Equals(standardEntity.Text))
                    .Select(w => new SelectItem(w.SecondLv, w.SecondLv)).ToArray();
                return SelectItem.ToItems(items, addDefault);
            });
        }

        /// <summary>
        /// 获取工程阶段
        /// </summary>
        /// <param name="projectId">项目id</param>
        /// <param name="addDefault"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetProjectStage(Guid projectId, bool addDefault = false)
        {
            return await TryCatchAsync(Task.Run(() =>
            {
                return Cached.GetOrSet(GetOpenApiName(), () =>
                {
                    var list = DataStore.GetStandards(projectId);
                    var items = list.Select(w => new SelectItem(w.Stage, w.ProjectStandardId.ToString())).ToArray();
                    return SelectItem.ToItems(items, addDefault);
                }, DataStore.GetCommonTimeSpan());
            }));
        }

        /// <summary>
        /// 获取标准库全部内容
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetList()
        {
            //已经弃用
            return await TryCatchAsync(Task.Run(() => { return StandardService.GetList(); }));
        }

        /// <summary>
        /// 获取本项目标准库全部内容
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetListByProject(Guid ProjectGuid)
        {
            //return await TryCatchAsync(Task.Run(() => { return StandardService.GetList(); }));
            return await TryCatchAsync(Task.Run(() => { return StandardService.GetListByProject(ProjectGuid); }));
        }

        /// <summary>
        /// 根据条件获取标准库信息
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetListCondition(StandardCondition condition)
        {
            return await TryCatchAsync(StandardService.GetListCondition(condition));
        }

        /// <summary>
        /// 获取标准库详情
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetStageStandard(StageStandardQueryDto obj)
        {
            return await TryCatch(async () =>
            {
                return await StandardService.GetStageStandard(obj);
            });
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Update(StandardListModel obj)
        {
            return await TryCatchAsync(StandardService.Update(obj));
        }

        /// <summary>
        /// 获取站点类型详情
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetPointTypeDetails(PointTypeCondition condition)
        {
            return await TryCatchAsync(StandardService.GetPointTypeDetails(condition.ProjectStandardId, condition.HouseMapId ?? Guid.Empty, condition.ProjectGuid));
        }

        /// <summary>
        /// 保存站点类型数据
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> SavePointTypeMeasureItem(List<MsPointTypeDto> models)
        {
            if (models == null || models.Count == 0)
            {
                throw new OperationException(localizer["YB0013"].Value);
            }
            return await TryCatchAsync(StandardService.Update(models));
        }

        /// <summary>
        /// 从基础标准库同步项目的标准库
        /// </summary>
        [HttpPost]
        [SwaggerResponse(0, "获取报告列表的字段：Result", typeof(ApiResultBase<UpdateResultDto>))]
        public async Task<ApiResult> UpdateFromBase(ProjectIdDto dto)
        {
            return await TryCatchAsync(StandardService.UpdateFromBase(dto.ProjectId));
        }
    }
}